import json
import logging
from easydict import EasyDict
from .tools import write_json, read_json, get_gitee_json
from .settings import PATH, URL


EMPTY_ACCOUNT = EasyDict({
    "username": "xxx",
    "black_wolf": ["18xxxxxxxxx", "password"],
    "fish_pond": ["18xxxxxxxxx", "password"],
    "taojiji": ["18xxxxxxxxx", "password"],
    "nanshanke": ["18xxxxxxxxx", "password"],
    "sea_pond": ["18xxxxxxxxx", "password"],
    "marking": ["18xxxxxxxxx", "password"],
    "taomeng": ["18xxxxxxxxx", "password"],
    "wanmuliyu": ["18xxxxxxxxx", "password"],
    "baodanbear": ["18xxxxxxxxx", "password"],
    "dazhou": ["18xxxxxxxxx", "password"],
    "yunying": ["18xxxxxxxxx", "password"],
    "sijiyou": ["18xxxxxxxxx", "password"],
    "burger": ["18xxxxxxxxx", "password"],
    "ecommerce_brain": ["18xxxxxxxxx", "password"],
    "magic_mirror": ["18xxxxxxxxx", "password"]
})

EMPTY_DEBUG = EasyDict({
    "black_wolf": False,
    "fish_pond": False,
    "taojiji": False,
    "nanshanke": False,
    "sea_pond": False,
    "marking": False,
    "taomeng": False,
    "wanmuliyu": False,
    "baodanbear": False,
    "dazhou": False,
    "yunying": False,
    "sijiyou": False,
    "burger": False,
    "ecommerce_brain": False,
    "magic_mirror": False
})

EMPTY_PLATFORM = EasyDict({
    "blacklist": True,
    "ecommerce_brain": True,
    "magic_mirror": False
})

EMPTY_USER = EasyDict({
    "name": "",
    "phone": [],
    "expire": "1921-7-1",
    "platform": []
})

ENTOZH = EasyDict({
    "username": "用户名",
    "blacklist": "黑名单",
    "black_wolf": "黑野狼",
    "fish_pond": "上下鱼塘",
    "taojiji": "陶吉吉",
    "nanshanke": "南山客",
    "sea_pond": "大海鱼塘",
    "marking": "精准打标",
    "taomeng": "淘盟",
    "wanmuliyu": "万亩鲤鱼",
    "baodanbear": "爆单熊",
    "dazhou": "大舟",
    "yunying": "韵营",
    "sijiyou": "四季柚",
    "burger": "小汉堡",
    "ecommerce_brain": "电商大脑",
    "magic_mirror": "照妖镜"
})

ZHTOEN = {v: k for k, v in ENTOZH.items()}


class Config:
    env_ok = False
    account = EMPTY_ACCOUNT
    debug = EMPTY_DEBUG
    platform = EMPTY_PLATFORM
    user = EMPTY_USER

    account_zh = EMPTY_ACCOUNT
    debug_zh = EMPTY_DEBUG
    platform_zh = EMPTY_PLATFORM

    def __init__(self, print_log=print):
        self.print_log = print_log
        self.init_files()
        self.print_log("开始加载配置信息...")
        try:
            self.env_ok = self.read_accounts()
            if self.env_ok:
                self.read_platform()
                self.read_debug()
                self.read_user()
                self.print_log("配置信息加载成功!\n")
        except Exception as e:
            self.print_log(f"配置信息加载失败，原因是: {e}\n")
            logging.exception(e)
            self.env_ok = False

    def init_files(self):
        if not PATH.account.is_file():
            write_json(PATH.account, EMPTY_ACCOUNT)

        if not PATH.debug.is_file():
            write_json(PATH.debug, EMPTY_DEBUG)

        if not PATH.platform.is_file():
            write_json(PATH.platform, EMPTY_PLATFORM)

    def read_accounts(self):
        try:
            self.account = read_json(PATH.account, EMPTY_ACCOUNT)
            self.account_zh = self.en2zh(self.account)
            if self.account == EMPTY_ACCOUNT:
                self.print_log("没有账号信息.请先配置账号信息后再重启软件.\n")
            else:
                self.print_log("账号信息加载成功！")
            return True
        except Exception as e:
            self.print_log(f"账号信息加载失败！原因是: {e}")
            self.print_log(f"请检查账号信息文件格式是否正确.\n")
            return False

    def read_debug(self):
        try:
            self.debug = read_json(PATH.debug, EMPTY_DEBUG)
            self.debug_zh = self.en2zh(self.debug)
            self.print_log("DEBUG信息加载成功！")
        except Exception as e:
            self.print_log(f"DEBUG信息加载失败！原因是: {e}")
            self.print_log("使用默认DEBUG信息.")

    def read_platform(self):
        try:
            self.platform = read_json(PATH.platform, EMPTY_PLATFORM)
            self.platform_zh = self.en2zh(self.platform)
            self.print_log("验号平台信息加载成功！")
        except Exception as e:
            self.print_log(f"验号平台信息加载失败！原因是: {e}")
            self.print_log("使用默认验号平台信息.")

    def read_user(self):
        user = get_gitee_json(URL.get_user_url(self.account.username))
        print(user)
        try:
            self.user = EasyDict(json.loads(user))
            assert "name" in self.user
        except Exception as e:
            self.user = EMPTY_USER
            self.print_log(f"该用户不存在，请重新配置！")
            self.print_log("使用默认用户信息.")

        if self.user.platform == "all":
            self.user.account = self.account_zh.keys()
            self.user.debug = self.debug_zh.keys()
        else:
            self.user.account = [ENTOZH[i] for i in self.user.platform] + ["电商大脑", "照妖镜", "用户名"]
            self.user.debug = [ENTOZH[i] for i in self.user.platform] + ["电商大脑", "照妖镜"]
        # self.print_log("用户信息加载成功！")

    def en2zh(self, data):
        new_data = EasyDict()
        for k, v in data.items():
            if k in ENTOZH:
                new_data[ENTOZH[k]] = v
            else:
                new_data[k] = v
        return new_data

    def zh2en(self, data):
        new_data = EasyDict()
        for k, v in data.items():
            if k in ZHTOEN:
                new_data[ZHTOEN[k]] = v
            else:
                new_data[k] = v
        return new_data

    def save_account(self):
        self.account = self.zh2en(self.account_zh)
        write_json(PATH.account, self.account)

    def save_platform(self):
        self.platform = self.zh2en(self.platform_zh)
        write_json(PATH.platform, self.platform)

    def save_debug(self):
        self.debug = self.zh2en(self.debug_zh)
        write_json(PATH.debug, self.debug)
